#ifndef __PROCESS_POOL_HPP__
#define __PROCESS_POOL_HPP__

#include <iostream>
#include <vector>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
#include "Task.hpp"
using namespace std;

class Pipe 
{
public:
    Pipe(int wfd, pid_t pid) //构造
        :_wfd(wfd), _pid(pid)
    {
        _pipe_name = "wfd为" + to_string(_wfd) + " --pipe-- 对应子进程pid是:" + to_string(_pid);
    }
    
    int Fd(){return _wfd;}
    pid_t Pid(){return _pid;}
    string Name(){return _pipe_name;}
    
    void SendCode(int code)
    {
        write(_wfd, &code, sizeof(code));
    }

    void Close() //关闭
    {
        close(_wfd); 
    }
    void Wait() //等待
    {
        waitpid(_wfd, nullptr, 0);
    }

    ~Pipe(){} //析构

private:
    int _wfd; //管道的读端文件描述符
    pid_t _pid; //管道对应的子进程pid
    string _pipe_name; //这个管道的名字
};

class ManagePipe
{
public:
    ManagePipe() 
        :_next(0) //next初始化0
    {}
    
    bool Insert(int wfd, pid_t pid)
    {
        _pipes.emplace_back(wfd, pid);
        return true;
    }
    void PrintPipsName() //打印一下管道的名字 
    {
        for(auto & p : _pipes)
        {
            cout << p.Name() << endl;
        }
    }

    Pipe &Select()
    {
        Pipe &p = _pipes[_next];
        _next++;
        _next %= _pipes.size(); //控制next的数值范围
        return p;
    }
    void CloseBeforAll()
    {
        for(auto & p:_pipes)
        {
            p.Close();
        }
    }
    void CloseAll()
    {
        for(auto & p:_pipes)
        {
            p.Close();
            cout << "关闭" << p.Name() << endl;
        }
    }

    void WaitAll()
    {
        for(auto & p:_pipes)
        {
            p.Wait();
            cout << "回收" << p.Name() << endl;
        }
    }

    ~ManagePipe()
    {}
private:
    vector<Pipe> _pipes; //用vector管理存放这些Pipe
    int _next; //记录下一个选谁
};


class ProcessPool
{
public:
    ProcessPool(int num = 5)
        :_proc_num(num)
    {
        _mt.Register(PrintLog);
        _mt.Register(DownLoad);
        _mt.Register(UpLoad);
    }

    void Work(int rfd)
    {
        while(1)
        {
            int code = 0;
            int n = read(rfd, &code, sizeof(code));
            if(n > 0) //读取成功
            {
                if(n != sizeof(code)) //读到的数据大小和发送的不一致
                    continue;
                cout << "子进程:" << getpid() << " 收到一个任务码：" << code << endl;
                _mt.Execute(code); //执行任务
            }
            else if(n == 0) //读取到文件结尾
            {
                cout << "子进程读取完毕" << endl;
                break;
            }
            else
            {
                cout << "读取失败" << endl;
                break;
            }
        }
    }
    bool Creat()
    {
        for(int i = 0; i < _proc_num; i++)
        {
            //1.创建管道
            int pipe_fd[2] = {0}; //pipe_fd[0]读端，pipe_fd[1]写端 
            int ret = pipe(pipe_fd);
            if(ret < 0) return false;//创建失败

            //2.创建子进程
            pid_t pid = fork();
            if(pid < 0) return false; 
            else if(pid == 0) //子进程
            {
                _mp.CloseBeforAll();//关闭之前打开过的写端
                //3.形成单向信道
                close(pipe_fd[1]);//子进程读，关闭pipe_fd(1)
                Work(pipe_fd[0]);
                close(pipe_fd[0]); //完成工作后把读端关掉
                exit(1); //然后直接退出
            }
            else //父进程
            {
                close(pipe_fd[0]);//父进程写,关闭pipe_fd(0)
                _mp.Insert(pipe_fd[1], pid);
            }
        }
        return true;
    }

    void PushTask()
    {
        //选择任务
        int task_code = _mt.Code();

        //选择信道
        Pipe &p = _mp.Select();
        cout << "选择了" << p.Name() << endl;

        //发送任务码
        cout << "发送任务码:" << task_code << endl;
        p.SendCode(task_code);
        
    }

    void Stop()
    {
        _mp.CloseAll();
        _mp.WaitAll();
    }

    void Debug()
    {
        _mp.PrintPipsName();
    }
    ~ProcessPool()
    {}

private:
    int _proc_num; //创建进程的数量
    ManagePipe _mp; //管理管道
    ManageTask _mt; //管理任务
};

#endif
